package com.webserver.core;

import com.webserver.http.HttpRequest;

import java.io.*;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理与指定客户端的HTTP交互
 * HTTP交互采取一问一答，因此这里分为三步完成一次交互过程：
 * 1：解析请求
 * 2：处理请求
 * 3：响应客户端
 */
public class ClientHandler implements Runnable{
    private Socket socket;
    public ClientHandler(Socket socket){
        this.socket=socket;
    }
    public void run(){
        try {

            //1解析请求
            HttpRequest request=new HttpRequest(socket);
            //2处理请求
            //通过请求对象获取浏览器URL中的抽象路径部分
            /*
            http://localhost:8088/myweb/index.html
            http://localhost:8088/myweb/classTable.html
            以下两种就是404情况
            http://localhost:8088/myweb/123/html
            http://localhost:8088 定位的是一个目录
             */
            String path=request.getUri();
            File file=new File("./webapps"+path);
            String line;
            if(file.exists()&&file.isFile()){
                //资源存在
                line="HTTP/1.1 200 OK";
            }else {
                //资源不存在
                line="HTTP/1.1 200 OK";
                file=new File("./webapps/root/404.html");
            }
            //3发送响应
            //将webapps/myweb/index.html回复给浏览器

            /*
            发送一个标准的响应头，大致如下：
            HTTP/1.1 200 OK(CRLF)
            Content-Type:text/html(CRLF)
            Content-length:2546(CRLF)(CRLF)
            10111010101010101010101101....
             */
            OutputStream out=socket.getOutputStream();
            //3.1:发送状态行
            byte[] data=line.getBytes("ISO8859-1");
            out.write(data);
            out.write(13);//written CR
            out.write(10);//written LF
            //3.2:发送响应头
            line="Content-Type:text/html";
            data=line.getBytes("ISO8859-1");
            out.write(data);
            out.write(13);//written CR
            out.write(10);//written LF
            line=" Content-length:"+file.length();
            data=line.getBytes("ISO8859-1");
            out.write(data);
            out.write(13);//written CR
            out.write(10);//written LF
            //单独发送CRLF表示响应头发送完毕
            out.write(13);//written CR
            out.write(10);//written LF
            //3.3:发送正文（index页面neir）
            FileInputStream fis=new FileInputStream(file);
            byte[] buf=new byte[1024*8];
            int len;
            while ((len=fis.read(buf))!=-1){
                out.write(buf,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                //交互端完毕后与客户端断开连接
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
